﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using GoodStuff.Web.Controls.Validation;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// Autovalidator generates validators based on the code-behind validation rules for the given control.
    /// </summary>
    public class AutoValidator : Control
    {
        private IEnumerable<ValidationRule> _rules;
        public IEnumerable<ValidationRule> Rules
        {
            get
            {
                return _rules;
            }
            set
            {
                _rules = value;
                CreateChildControls();
            }
        }

        protected override void CreateChildControls()
        {
            this.Controls.Clear();
            foreach (ValidationRule rule in _rules)
            {
                //find the control to render.
                Control target = this.Parent.FindControl(ControlToValidate);
                if (target == null)
                {
                    throw new Exception("Cannot target '" + ControlToValidate + "'");
                }

                //inject the client validator
                BaseValidator validator = rule.CreateValidatorFor(target);
                if (validator != null)
                {
                    switch (Pattern)
                    {
                        case ValidationMessagePattern.AsText:
                            validator.Text = rule.Message;
                            break;
                        case ValidationMessagePattern.AsSummary:
                            validator.Text = "*";
                            validator.ErrorMessage = rule.Message;
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }


                    validator.ControlToValidate = ControlToValidate;
                    validator.Display = ValidatorDisplay.Dynamic;
                    this.Controls.Add((Control)validator);
                }
            }
            this.ChildControlsCreated = true;
        }

        public string Key { get; set; }
        public string ControlToValidate { get; set; }

        public ValidationMessagePattern Pattern { get; set; }
    }        
}
